package com.jt.security.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 默认的访问用于处理访问被拒绝的异常处理器对象
 * 1.Default-默认
 * 2.Access-访问
 * 3.Denied-拒绝
 * 4.Exception-异常
 * 5.Hander-处理器
 * */
public class DefaultAccessDeniedExceptionHandler implements AccessDeniedHandler {

    /**
     * 此方法用于处理AccessDeniedException对象
     * @paramhttpServletRequest 请求对象
     * @paramhttpServletResponse 响应对象
     * @paramexception 访问被拒绝的的异常对象
     * @throwsIOException
     * @throwsServletException
     * */
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException exception)
            throws IOException, ServletException {
        //方案1:从定向
        //httpServletResponse.sendRedirect("http://www.baidu.com");

        //方案2:假如访问被拒绝了向客户端响应一个json格式的字符串
        //设置响应数据的编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉浏览器响应数据的内容类型以及编码
        httpServletResponse.setContentType("application/json,charset=utf-8");
        //获取输出流对象
        PrintWriter out = httpServletResponse.getWriter();
        //将数据输出到客户端
        //封装数据
        Map<String,Object> map = new HashMap<>();
        map.put("state",HttpServletResponse.SC_FORBIDDEN);//SC_FORBIDDEN的值是403
        map.put("message","没有访问权限,请联系管理员");
        //将数据装换为json格式字符串
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        //输出数据
        out.println(jsonStr);
        out.flush();




    }
}
